﻿namespace LevelEditors
{
    using System;
    using System.Runtime.CompilerServices;
    using UnityEngine;
    using UnityEngine.EventSystems;

    public class LevelEditorCamera : MonoBehaviour
    {
        private static string dataStr;
        private Vector3 lastMousePos;
        private static LevelEditorCamera m_Instance;
        private int pixelLightCount;
        public float scrollSpeed = 1f;

        private void Awake()
        {
            this.cam = base.GetComponent<Camera>();
            if (!string.IsNullOrEmpty(dataStr))
            {
                Data data = JsonUtility.FromJson<Data>(dataStr);
                data.position.y = 8f;
                base.transform.position = data.position;
                this.cam.orthographicSize = data.orthographicSize;
            }
            this.pixelLightCount = QualitySettings.pixelLightCount;
        }

        private void OnDestroy()
        {
            Data data = new Data {
                position = base.transform.position,
                orthographicSize = this.cam.orthographicSize
            };
            dataStr = JsonUtility.ToJson(data);
            QualitySettings.pixelLightCount = this.pixelLightCount;
        }

        private void Update()
        {
            if (!EventSystem.current.IsPointerOverGameObject() && !this.isMouseOverGUI)
            {
                Vector3 zero = this.cam.GetWorldPositionOnPlaneXZ(Input.mousePosition, 0f) - this.cam.GetWorldPositionOnPlaneXZ(this.lastMousePos, 0f);
                if (Input.GetMouseButtonDown(2))
                {
                    zero = Vector3.zero;
                }
                if (Input.GetMouseButton(2))
                {
                    Transform transform = base.transform;
                    transform.position += -zero;
                }
                this.lastMousePos = Input.mousePosition;
                Camera cam = this.cam;
                cam.orthographicSize -= Input.GetAxis("Mouse ScrollWheel") * this.scrollSpeed;
                this.cam.orthographicSize = Mathf.Clamp(this.cam.orthographicSize, 1f, 30f);
                QualitySettings.pixelLightCount = (int) Mathf.Lerp((float) this.pixelLightCount, 0f, this.cam.orthographicSize / 20f);
            }
        }

        public Camera cam { get; private set; }

        public static LevelEditorCamera Instance
        {
            get
            {
                return ((m_Instance == null) ? (m_Instance = UnityEngine.Object.FindObjectOfType<LevelEditorCamera>()) : m_Instance);
            }
        }

        private bool isMouseOverGUI
        {
            get
            {
                return ((GUIUtility.hotControl > 0) || GameConsole.isMouseOverConsoleGUI);
            }
        }

        [Serializable]
        public class Data
        {
            public float orthographicSize;
            public Vector3 position;
        }
    }
}

